package cn.edu.tsinghua.xkk.correction;

import cn.edu.tsinghua.xkk.recommendation.EditDistance;

import java.util.LinkedList;
import java.util.List;
import java.io.RandomAccessFile;

public class Dictionary_en
{
	public List <String> contents;
	public WholeIndex[] index;
	public int indexNum = 6;
	public EditDistance ted = new EditDistance();
	
	public Dictionary_en(String location)
	{
		contents = new LinkedList <String> ();
		index = new WholeIndex[indexNum];
		
		for (int i = 0; i < indexNum; i++)
		{
			index[i] = new WholeIndex ();
		}
		try
		{
			RandomAccessFile reader= new RandomAccessFile (location, "r");
			
			while (true)
			{
				String tmp = reader.readLine();
				if (tmp == null) break;
				contents.add(tmp);
				
				for (int i = 0; i < indexNum && i < tmp.length(); i++)
				{
					index[i].add(tmp, contents.size() - 1);
					tmp = (tmp.substring(1)).concat(tmp.substring(tmp.length() - 1));
				}
			}
		}
		catch (Exception e)
		{
		}
	}
	
	public String search (String target)
	{
		List <String> answer = new LinkedList <String> ();
		List <Integer> nums = new LinkedList <Integer> ();
		String tmp = target;
		
		for (int i = 0; i < indexNum && i < target.length(); i++)
		{
			nums.addAll(index[i].search(tmp));
			tmp = (tmp.substring(1)).concat(tmp.substring(tmp.length() - 1));
		}
		
		for (int i = 0; i < nums.size(); i++)
		{
			for (int j = 0; j < i; j++)
			{
				if (nums.get(i) == nums.get(j))
				{
					nums.remove(i);
					i--;
					break;
				}
			}
		}
		
		for (int i = 0; i < nums.size(); i++)
		{
			answer.add(contents.get(nums.get(i)));
		}
		
		double max = 0;
		int pos = 0;
		
		for (int i = 0; i < answer.size(); i++)
		{
			double tmp1 = ted.sim(target, answer.get(i));
			if (max < tmp1)
			{
				max = tmp1;
				pos = i;
			}
		}
		
		if (answer.size() == 0)
		{
			return target;
		}
		return answer.get(pos);
	}
}
